//index.js
const app = getApp()

Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    logged: false,
    takeSession: false,
    requestResult: '',
    bgImg:false,
    bgImgId:false
  },

  onLoad: function(opt) {
    if (opt.soundId) {
      wx.navigateTo({
        url: '/pages/detail/index?soundId='+opt.soundId+'&imgId='+opt.imgId,
      })
      return
    }

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })
  },

   onGetUserInfo: async function(e) {
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
    await this.onGetOpenid()
      wx.cloud.callFunction({
        name: 'updateUser',
        data: {
          openid:app.globalData.openid,
          user:e.detail.userInfo
        },
        success: res => {
          console.log('[云函数] [update] user openid: ', res)
          console.log(res)
  
          this.setData({
            userInfo:res.result.userInfo
          })
        },
        fail: err => {
          console.error('[云函数] [update] 调用失败', err)
  
        }
      })
    
    
  },

  onGetOpenid: function() {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        console.log(res)
        app.globalData.openid = res.result.openid
        // wx.navigateTo({
        //   url: '../userConsole/userConsole',
        // })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        // wx.navigateTo({
        //   url: '../deployFunctions/deployFunctions',
        // })
      }
    })
  },
  startRecord(e) {
    console.log('startRecord')
    wx.startRecord({
        success: (res) => {
            console.log('startRecord succ')
            this.recordPath = res.tempFilePath;

            this.uploadRecord(res.tempFilePath);
        },
        fail: () => {
            console.log('startRecord|失败')
        }
    })
},
endRecord(e) {
    console.log('endRecord..');
    wx.stopRecord();
},
uploadRecord:function (res) {
  let filePath = res
  wx.showLoading({
    title: '上传中',
  })
  let len = filePath.split('//').length
  const cloudPath = 'sound/'+filePath.split('//')[len-1];
  console.log(cloudPath)
  wx.cloud.uploadFile({
    cloudPath,
    filePath,
    success: res => {
      console.log('[上传文件] 成功：', res)

      app.globalData.fileID = res.fileID
    
      
    },
    fail: e => {
      console.error('[上传文件] 失败：', e)
      wx.showToast({
        icon: 'none',
        title: '上传失败',
      })
    },
    complete: () => {
      wx.hideLoading()
    }
  })
},

listen:async function(){
  await wx.cloud.downloadFile({
    fileID: app.globalData.fileID,
    success: res => {
      // 返回临时文件路径
      console.log(res.tempFilePath)

      wx.playVoice({
        filePath: res.tempFilePath,
        complete: () => {
         
            console.log('playSound|play sound end')
        
        }
    })
    },
    fail: console.error
  })
 
},


  // 上传图片
  doUpload: function () {
    let that =this;
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {

        wx.showLoading({
          title: '上传中',
        })

        const filePath = res.tempFilePaths[0]
        
        // 上传图片
        
       
        let len = filePath.split('//').length
        const cloudPath = 'images/' + filePath.split('//')[len-1]
        
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[上传文件] 成功：', res)
            console.log(filePath)
      
            that.setData({
              bgImg:filePath,
              bgImgId:res.fileID
            })
            
            // wx.navigateTo({
            //   url: '../storageConsole/storageConsole'
            // })
          },
          fail: e => {
            console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })

      },
      fail: e => {
        console.error(e)
      }
    })
  },
  
  previewImg: function(){
    let that =this;
    console.log(this.data.bgImg)
    if(!that.data.bgImg){
      return
    }
  
   let img = that.data.bgImg
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: [img] // 需要预览的图片http链接列表
    })
  },
  getQrcode:function(){
    wx.cloud.callFunction({
      name: 'getQrcode',
      data: {
        path:'pages/index?soundId='+ app.globalData.fileID
      },
      success: res => {
        console.log('[云函数] [qrcode] 调用成功', res)
      },
      fail: err => {
        console.error('[云函数] [qrcode] 调用失败', err)
       
      }
    })
  },
  onShareAppMessage(res) {
    if (res.from === 'button') {
        console.log("来自页面内转发按钮");
        if (res.target.dataset.from == "share") {
           
            return {
                title: `来自${this.data.userInfo.nickName}对你的生日祝福`,
                imageUrl: '../../images/bg.jpeg',
                path: '/pages/index/index?soundId='+ app.globalData.fileID+'&imgId='+this.data.bgImgId,
                success: (res) => {
                    console.log("succ");

                }
            }
        }
    }
    return {
        title: `在这里有破壳日的祝福`,
        imageUrl: '../../images/bg.jpeg',
        path: '/pages/index/index',
        success: (res) => {
            console.log("succ");

        }
    }
}
})
